<template>
  <view :class="['index', `theme-${currentTheme}`]">
    <!-- 数据安全/隐私政策提示图标 -->
    <view class="data-security-icon" v-if="!showDataSecurityTip" @tap="showDataSecurityTip = true">
      <text class="security-icon iconfont icon-info"></text>
    </view>
    
    <!-- 数据安全提示 包含隐私政策内容 -->
    <view class="data-security-tip" v-if="showDataSecurityTip">
      <view class="tip-content">
        <view class="tip-title">数据安全与隐私政策</view>
        <view class="tip-text">
          <text>· 为尊重用户数据隐私，本应用所有数据均存储在本地，未上传至服务器，请及时备份您的数据</text>
          <text>· 以下情况可能导致数据丢失：清理小程序缓存、卸载小程序、手机重置等</text>
          <text>· 建议定期在【设置】中进行数据备份，备份文件可用于数据恢复</text>
          <text class="highlight">· 点击"查看隐私政策"可了解详细的隐私协议内容</text>
        </view>
        <view class="tip-actions">
          <button class="action-btn privacy" @tap="openPrivacyPolicyDirectly">查看隐私政策</button>
          <button class="action-btn backup" @tap="goToBackup">立即备份</button>
          <button class="action-btn close" @tap="closeDataSecurityTip">我知道了</button>
        </view>
      </view>
    </view>

    <!-- 统计卡片 -->
    <view class="stats-card">
      <view class="stats-item">
        <text class="value">{{ formatAmount(totalReceived) }}</text>
        <text class="label">收到礼金</text>
      </view>
      <view class="stats-item">
        <text class="value">{{ formatAmount(totalGiven) }}</text>
        <text class="label">送出礼金</text>
      </view>
      <view class="stats-item">
        <text class="value">{{ contactCount }}</text>
        <text class="label">联系人</text>
      </view>
    </view>

    <!-- 快捷操作 -->
    <view class="quick-actions">
      <view class="action-item" @click="navigateTo('/pages/giftbook/add')">
        <text class="iconfont icon-add"></text>
        <text class="label">新建礼簿</text>
      </view>
      <view class="action-item" @click="navigateTo('/pages/contact/add')">
        <text class="iconfont icon-user-add"></text>
        <text class="label">添加联系人</text>
      </view>
      <view class="action-item" @click="navigateTo('/pages/statistics/index')">
        <text class="iconfont icon-chart"></text>
        <text class="label">查看统计</text>
      </view>
      <view class="action-item" @click="toggleTheme">
        <text class="iconfont" :class="currentTheme === ThemeType.FUNERAL ? 'icon-sad' : 'icon-happy'"></text>
        <text class="label">{{ currentThemeLabel }}</text>
      </view>
    </view>

    <!-- 最近记录 -->
    <view class="recent-records">
      <view class="section-title">
        <text class="title">最近记录</text>
        <text class="link-text" @click="switchTab('/pages/giftbook/index')">查看更多</text>
      </view>
      <view v-if="recentRecords.length > 0" class="records-list">
        <view v-for="record in recentRecords" :key="record.id" class="record-item" @click="navigateToDetail(record.giftBookId)">
          <view class="record-info">
            <text class="title">{{ record.title }}</text>
          </view>
          <view class="record-right">
            <text class="contact-name">{{ record.contactName }}</text>
            <text class="amount" :class="{'amount-receive': record.type === 'receive', 'amount-give': record.type === 'give'}">
              {{ record.type === 'receive' ? '+' : '-' }}¥{{ formatAmount(record.amount) }}
            </text>
          </view>
        </view>
      </view>
      <view v-else class="empty-state">
        <view class="empty-icon">
          <text class="iconfont icon-empty"></text>
        </view>
        <text class="empty-text">暂无记录</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useGiftBookStore } from '@/store/modules/giftbook';
import { useContactStore } from '@/store/modules/contact';
import { useThemeStore, ThemeType } from '@/store/modules/theme';
import { useSettingsStore } from '@/store/modules/settings';
import { GiftRecordType } from '@/types/giftbook';
import type { GiftBook, GiftRecord } from '@/types/giftbook';
import type { Contact } from '@/types/contact';
import useThemeMixin from '@/mixins/themeMixin';

const giftBookStore = useGiftBookStore();
const contactStore = useContactStore();
const themeStore = useThemeStore();
const settingsStore = useSettingsStore();

// 数据安全提示显示状态
const showDataSecurityTip = ref(false);

// 从本地存储获取提示显示状态
const loadTipStatus = () => {
  try {
    const tipShown = uni.getStorageSync('data_security_tip_shown');
    if (tipShown) {
      showDataSecurityTip.value = false;
    } else {
      // 如果是首次访问，显示提示
      showDataSecurityTip.value = true;
    }
  } catch (error) {
    console.error('获取提示状态失败:', error);
  }
};

// 关闭数据安全提示
const closeDataSecurityTip = () => {
  showDataSecurityTip.value = false;
  try {
    uni.setStorageSync('data_security_tip_shown', 'true');
  } catch (error) {
    console.error('保存提示状态失败:', error);
  }
};

// 从数据安全提示中直接打开隐私政策
const openPrivacyPolicyDirectly = () => {
  console.log('从数据安全提示中打开隐私政策页面');
  
  // 先关闭当前提示
  showDataSecurityTip.value = false;
  
  // 导航到隐私政策页面
  uni.navigateTo({
    url: '/pages/settings/privacy'
  });
};

// 当前主题
const currentTheme = computed(() => themeStore.currentTheme);

// 使用主题mixin
useThemeMixin();

// 主题标签映射
const themeLabels: Record<ThemeType, string> = {
  [ThemeType.WEDDING]: '婚礼',
  [ThemeType.FUNERAL]: '白事',
  [ThemeType.BIRTHDAY]: '生日',
  [ThemeType.GRADUATION]: '升学',
  [ThemeType.BUSINESS]: '商务',
  [ThemeType.HOUSEWARMING]: '乔迁',
  [ThemeType.FULLMOON]: '满月',
  [ThemeType.OTHER]: '其他'
};

// 主题顺序
const themeOrder = [
  ThemeType.WEDDING,
  ThemeType.FUNERAL,
  ThemeType.BIRTHDAY,
  ThemeType.GRADUATION,
  ThemeType.BUSINESS,
  ThemeType.HOUSEWARMING,
  ThemeType.FULLMOON,
  ThemeType.OTHER
];

// 当前主题标签
const currentThemeLabel = computed(() => themeLabels[currentTheme.value as ThemeType]);

// 切换主题
const toggleTheme = () => {
  const currentIndex = themeOrder.indexOf(currentTheme.value);
  const nextIndex = (currentIndex + 1) % themeOrder.length;
  themeStore.setTheme(themeOrder[nextIndex]);
};

// 统计数据
const totalReceived = computed(() => {
  return giftBookStore.getAllGiftBooks.reduce((total: number, book: GiftBook) => {
    if (book.totalReceived) {
      return total + book.totalReceived;
    }
    // 兼容旧数据，如果没有totalReceived则计算
    return total + book.records.reduce((sum: number, record: GiftRecord) => {
      return sum + (record.type === 'receive' ? Number(record.amount) : 0);
    }, 0);
  }, 0);
});

const totalGiven = computed(() => {
  return giftBookStore.getAllGiftBooks.reduce((total: number, book: GiftBook) => {
    if (book.totalGiven) {
      return total + book.totalGiven;
    }
    // 兼容旧数据，如果没有totalGiven则计算
    return total + book.records.reduce((sum: number, record: GiftRecord) => {
      return sum + (record.type === 'give' ? Number(record.amount) : 0);
    }, 0);
  }, 0);
});

const contactCount = computed(() => contactStore.getAllContacts.length);

interface ExtendedGiftRecord extends GiftRecord {
  giftBookId: string;
  title: string;
  createdAt?: number; // 兼容旧接口
}

// 最近记录
const recentRecords = computed(() => {
  const allRecords: ExtendedGiftRecord[] = [];
  
  giftBookStore.getAllGiftBooks.forEach((book: GiftBook) => {
    book.records.forEach((record: GiftRecord) => {
      allRecords.push({
        ...record,
        giftBookId: book.id,
        title: book.title,
        createdAt: record.createTime // 确保兼容性
      });
    });
  });
  
  return allRecords
    .sort((a: ExtendedGiftRecord, b: ExtendedGiftRecord) => 
      b.createTime - a.createTime // 使用createTime而不是createdAt
    )
    .slice(0, 5);
});

// 获取记录类型标签
const getRecordTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    'receive': '收到',
    'give': '送出'
  };
  return typeMap[type] || '其他';
};

// 页面跳转
const navigateTo = (url: string) => {
  uni.navigateTo({ url });
};

const switchTab = (url: string) => {
  uni.switchTab({ url });
};

const navigateToDetail = (giftBookId: string) => {
  navigateTo(`/pages/giftbook/detail?id=${giftBookId}`);
};

// 前往备份页面
const goToBackup = () => {
  navigateTo('/pages/settings/index');
};

// 初始化数据
onMounted(async () => {
  console.log('首页挂载完成，即将加载数据和隐私状态');
  
  // 初始化数据
  await Promise.all([
    giftBookStore.loadFromStorage(),
    contactStore.loadContacts(),
    themeStore.initTheme(),
    settingsStore.loadSettings()
  ]);
  
  // 加载完成后再检查隐私政策状态
  setTimeout(() => {
    loadTipStatus();
  }, 300);
});

// 格式化金额，整数不显示小数点
const formatAmount = (amount: number) => {
  if (amount === undefined || amount === null) return '0';
  
  // 对大金额进行简化处理
  if (amount >= 100000000) { // 亿
    const value = amount / 100000000;
    return (Number.isInteger(value) ? value.toString() : value.toFixed(2)) + '亿';
  } else if (amount >= 10000) { // 万
    const value = amount / 10000;
    return (Number.isInteger(value) ? value.toString() : value.toFixed(2)) + '万';
  }
  
  // 整数金额不显示小数点后的零
  return Number.isInteger(amount) ? amount.toString() : amount.toFixed(2);
};
</script>

<style lang="scss">
.index {
  padding: $spacing-lg;
  min-height: 100vh;
  background-color: var(--background-color);
  position: relative;
  
  &.theme-funeral {
    --primary-color: #2c3e50;
    --primary-dark: #1a2634;
    --primary-light: #F5F5F5;
  }
  
  .data-security-icon {
    position: fixed;
    right: 30rpx;
    bottom: 100rpx;
    width: 80rpx;
    height: 80rpx;
    background-color: var(--primary-color);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.2);
    z-index: 10;
    animation: pulse 2s infinite;
    
    .security-icon {
      color: #fff !important;
      font-size: 40rpx;
    }
  }
  
  .data-security-tip {
    position: fixed;
    right: 30rpx;
    bottom: 100rpx;
    width: 80%;
    max-width: 600rpx;
    z-index: 100;
    animation: slideIn 0.3s ease-out;
    
    @keyframes slideIn {
      from {
        opacity: 0;
        transform: translateY(20rpx);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }
    
    .tip-content {
      padding: $spacing-lg;
      background-color: #fff;
      border-radius: $border-radius-lg;
      box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
      
      .tip-title {
        font-size: 32rpx;
        font-weight: bold;
        color: var(--text-primary);
        margin-bottom: $spacing-sm;
      }
      
      .tip-text {
        margin-bottom: $spacing-md;
        
        text {
          display: block;
          font-size: 28rpx;
          color: var(--text-secondary);
          line-height: 1.6;
          margin-bottom: 8rpx;
          
          &.highlight {
            color: var(--primary-color);
            font-weight: bold;
          }
        }
      }
      
      .tip-actions {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        
        .action-btn {
          background: none;
          padding: 10rpx 30rpx;
          font-size: 28rpx;
          border-radius: 40rpx;
          margin: 10rpx;
          width: 45%;
          
          &.privacy {
            background-color: var(--primary-color);
            color: #ffffff;
          }
          
          &.backup {
            background-color: var(--primary-color);
            color: #ffffff;
          }
          
          &.close {
            background-color: #f8f8f8;
            color: var(--text-secondary);
            width: 90%;
          }
          
          &:after {
            border: none;
          }
        }
      }
    }
  }
  
  .stats-card {
    border-radius: $border-radius-lg;
    padding: $spacing-lg;
    margin-bottom: $spacing-lg;
    display: flex;
    justify-content: space-around;
    background-color: var(--primary-color);
    box-shadow: 0 4rpx 12rpx rgba($color: #000000, $alpha: 0.1);
    transition: all 0.3s ease;
    
    .stats-item {
      text-align: center;
      
      .value {
        display: block;
        font-size: 48rpx;
        font-weight: bold;
        color: #ffffff;
        margin-bottom: $spacing-xs;
      }
      
      .label {
        font-size: 24rpx;
        color: rgba(#ffffff, 0.9);
      }
    }
  }
  
  .quick-actions {
    background-color: #ffffff;
    border-radius: $border-radius-lg;
    padding: $spacing-lg;
    margin-bottom: $spacing-lg;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: $spacing-md;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    
    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .iconfont {
        font-size: 48rpx;
        margin-bottom: $spacing-sm;
        transition: transform $animation-duration;
        color: var(--primary-color);
      }
      
      .label {
        font-size: 24rpx;
        color: var(--text-secondary);
      }
      
      &:active {
        .iconfont {
          transform: scale(0.9);
        }
      }
    }
  }
  
  .recent-records {
    background-color: #ffffff;
    border-radius: $border-radius-lg;
    padding: $spacing-lg;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    
    .section-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: $spacing-md;
      
      .title {
        font-size: 32rpx;
        font-weight: bold;
        color: var(--text-primary);
      }

      .link-text {
        color: var(--primary-color);
        font-size: 24rpx;
      }
    }
    
    .records-list {
      .record-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: $spacing-lg 0;
        border-bottom: 2rpx solid var(--border-color);
        
        &:last-child {
          border-bottom: none;
        }
        
        .record-info {
          flex: 1;
          
          .title {
            font-size: 30rpx;
            color: var(--text-primary);
            font-weight: 500;
          }
        }
        
        .record-right {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          
          .contact-name {
            font-size: 26rpx;
            color: var(--text-secondary);
            margin-right: 24rpx;
            background-color: rgba(0, 0, 0, 0.03);
            padding: 4rpx 12rpx;
            border-radius: 20rpx;
          }
          
          .amount {
            font-size: 32rpx;
            font-weight: bold;
            min-width: 140rpx;
            text-align: right;
            
            &.amount-receive {
              color: #67c23a !important;
            }
            
            &.amount-give {
              color: #f56c6c !important;
            }
          }
        }
      }
    }
    
    .empty-state {
      padding: $spacing-xl 0;
      text-align: center;
      
      .empty-icon {
        margin-bottom: $spacing-md;
        
        .iconfont {
          font-size: 96rpx;
          color: var(--text-secondary);
        }
      }
      
      .empty-text {
        font-size: 28rpx;
        color: var(--text-secondary);
      }
    }
  }
}
</style> 